package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.RequestParam;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Resource
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParam dto) {
        /*
        从ES里面查询我们要的数据
         */
        // 2.创建请求对象
        SearchRequest request = new SearchRequest("hotel");

        // 3.组装DSL参数
        basicQuery(request,dto);

        // 定位判断，根据地理位置排序
        if (!StringUtils.isEmpty(dto.getLocation())) {
            request.source().sort(
                    SortBuilders.geoDistanceSort("location", new GeoPoint(dto.getLocation()))
                            .order(SortOrder.ASC)
                            .unit(DistanceUnit.KILOMETERS)
            );
        } else if (!StringUtils.isEmpty(dto.getSortBy()) && ("price".

                equals(dto.getSortBy()) || "score".

                equals(dto.getSortBy()))) {
            request.source().sort(dto.getSortBy(), SortOrder.ASC);
        }

        // 3.2 分页
        request.source().

                from((dto.getPage() - 1) * dto.getSize()).

                size(dto.getSize());

        // 1.发送请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (
                IOException e) {
            log.error(e.getMessage());
            throw new RuntimeException();
        }

        // 4.解析结果
        return handleResponse(response, dto);

    }

    /*
    基本查询
     */
    private void basicQuery(SearchRequest request, RequestParam dto) {

        // 创建Bool查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();

        // 3.1 关键字查询
        String key = dto.getKey();
        if (!StringUtils.isEmpty(key)) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("all", dto.getKey()));
        } else {
            boolQueryBuilder.must(QueryBuilders.matchAllQuery());
        }

        // 城市过滤
        String city = dto.getCity();
        if (!StringUtils.isEmpty(city)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("city", city));
        }

        // 品牌
        String brand = dto.getBrand();
        if (!StringUtils.isEmpty(brand)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brand", brand));
        }

        // 星级
        String starName = dto.getStarName();
        if (!StringUtils.isEmpty(starName)) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("starName", starName));
        }

        // 价格
        if (dto.getMaxPrice() != null && dto.getMinPrice() != null) {
            boolQueryBuilder.filter(QueryBuilders.rangeQuery("price").gte(dto.getMinPrice()).lte(dto.getMaxPrice()));
        }


        // 创建算分函数查询
        FunctionScoreQueryBuilder functionScoreQueryBuilder = QueryBuilders.functionScoreQuery(boolQueryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10))
                });

        // 设定布尔查询
        request.source().query(functionScoreQueryBuilder);
    }


    /**
     * 聚合结果
     * @param dto
     */
    @Override
    public Map<String, List<String>> filters(RequestParam dto) {

        // 先准备好容器，用来放聚合好的值
        Map<String,List<String>> resultMap = new HashMap<>();

        // 1. 创建请求对象
        SearchRequest request = new SearchRequest("hotel");
        // 2. 组装DSL参数

        // 限定查询的范围 query
        basicQuery(request,dto);

        // 2.1 聚合
        createAggs(request);

        // 3. 发起请求
        SearchResponse response = null;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 4. 解析结果
        // 4.1 品牌聚合结果
        List<String> brandList = handleAggResult(response,"brand_agg");
        resultMap.put("brand",brandList);

        // 4.1 城市聚合结果
        List<String> cityList = handleAggResult(response,"city_agg");
        resultMap.put("city",cityList);


        // 4.1 星级聚合结果
        List<String> starList = handleAggResult(response,"star_agg");
        resultMap.put("starName",starList);

        return resultMap;
    }


    /**
     * 组装DSL---聚合
     * @param request
     */
    private void createAggs(SearchRequest request) {
        // 2.1 限定文档数量
        request.source().size(0);
        // 2.2 品牌聚合
        request.source().aggregation(
                AggregationBuilders.terms("brand_agg")
                        .field("brand")
                        .size(10)
        );
        // 2.3 城市聚合
        request.source().aggregation(
                AggregationBuilders.terms("city_agg")
                        .field("city")
                        .size(10)
        );
        // 2.4 星级
        request.source().aggregation(
                AggregationBuilders.terms("star_agg")
                        .field("starName")
                        .size(10)
        );
    }

    /**
     * 解析聚合结果
     */
    private List<String> handleAggResult(SearchResponse response, String aggName){
        List<String> aggList = new ArrayList<>();
        // 4.1 获取聚合结果
        Aggregations aggregations = response.getAggregations();
        // 4.2 根据名称获取具体聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.3 获取桶的集合
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.4 遍历
        for (Terms.Bucket bucket : buckets) {
            // 获取Key
            aggList.add(bucket.getKeyAsString());
        }
        return aggList;
    }

    /**
     * 结果进行解析
     *
     * @param response
     */
    private PageResult handleResponse(SearchResponse response, RequestParam dto) {

        PageResult pageResult = new PageResult();

        // 4.解析结果
        // 4.1 获取外层Hits
        SearchHits hits = response.getHits();
        long total = hits.getTotalHits().value;
        // 条数设定
        pageResult.setTotal(total);

        System.out.println("数据总条数" + total);

        // Source字段的最后结果要封装到List
        List<HotelDoc> hotels = new ArrayList<>();
        // 4.2 获取里层hits
        HotelDoc hotelDoc = null;
        SearchHit[] innerHits = hits.getHits();
        for (SearchHit innerHit : innerHits) {
            // 解析source
            // 反序列化JSON为HotelDoc对象
            hotelDoc = JSON.parseObject(innerHit.getSourceAsString(), HotelDoc.class);
            // 解析highlight
            Map<String, HighlightField> highlightFields = innerHit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                HighlightField field = highlightFields.get("name");
                if (field != null) {
                    // 拿到高亮字符串
                    // 将当前HotelDoc对象的name值进行替换
                    hotelDoc.setName(field.getFragments()[0].toString());
                }
            }

            // 存在坐标信息的时候我们才去取距离信息（修改其他排序条件存在的Bug）
            if (!StringUtils.isEmpty(dto.getLocation())) {
                // 解析排序距离
                Object[] sortValues = innerHit.getSortValues();
                if (sortValues != null && sortValues.length > 0) {
                    // 将距离设定到HotelDoc对象中
                    hotelDoc.setDistance(sortValues[0]);
                }
            }

            // 到此，HotelDoc组装完毕，将对象放入List
            hotels.add(hotelDoc);
        }

        // 到此，hotels组装完毕
        pageResult.setHotels(hotels);

        return pageResult;
    }
}
